package cn.ligui.exportsis.service;

import cn.ligui.exportsis.bean.AssetTagInfo;
import cn.ligui.exportsis.bean.TagData;
import cn.ligui.exportsis.bean.TagResponse;
import cn.ligui.exportsis.enums.TimeEnum;
import cn.ligui.exportsis.utils.CSVUtil;
import cn.ligui.exportsis.utils.HttpClientUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.LongSerializationPolicy;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: ligui
 * @CreateTime: 2023-07-31 10:02
 * @Description:
 */
@Slf4j
public class DataSyncService {



    public static final String sisUrl = "https://wiki.sis2.wsd.gov/sis3/webresources/histories";

    static List<String> titleList = new ArrayList<String>() {{
        add("ID");
        add("时间");
        add("数值");
    }};

    static List<String> fieldList = new ArrayList<String>() {{
        add("tag");
        add("time");
        add("value");
    }};

    public static void getData(String startDateStr, String endDateStr) throws ParseException, IOException {
        String dirName = "sis-data/" + startDateStr.replaceAll("-", "") + "-" + endDateStr.replaceAll("-", "");
        File dir = new File(dirName);
        try {
            // 如果文件不存在，则创建这个文件
            if (!dir.exists()) {
                boolean result = dir.mkdirs();
                if (result) {
                    log.info("Create folder successful：" + dir.getAbsolutePath());
                } else {
                    log.info("Create folder fail");
                }
            } else {
                log.info("The folder already exists:" + dir.getAbsolutePath());
            }
        } catch (Exception e) {
            log.error("Create folder fail");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startTime = sdf.parse(startDateStr);
        Date endTime = sdf.parse(endDateStr);

        SimpleDateFormat zSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
        SimpleDateFormat nSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        List<AssetTagInfo> tagList = CommonService.getTagList();
        for (AssetTagInfo assetTagInfo : tagList) {
            List<TagData> allDataList = new ArrayList<>();
            getSisData(assetTagInfo.getSisTag(), startTime, endTime, TimeEnum.DAY, allDataList);

            if (!allDataList.isEmpty()) {
                for (TagData tagData : allDataList) {
                    String time = tagData.getTime();
                    Date parse = zSdf.parse(time);
                    tagData.setTime(nSdf.format(parse));
                    tagData.setTag(assetTagInfo.getName());
                }
            }

            CSVUtil.exportDataFile(allDataList,titleList,fieldList,dirName + "\\",
                    assetTagInfo.getSisTag().replaceAll("/","-"));
        }
    }

    public static void getSisData(String tag, Date startTime, Date endTime, TimeEnum timeEnum, List<TagData> allDataList){
        Gson gson = new Gson();

        String responseStr = doGetSisInterface(tag, startTime, endTime);

        if (StringUtils.isNotBlank(responseStr)) {
            Map<String, Object> json = gson.fromJson(responseStr, new TypeToken<Map<String, Object>>() {
            }.getType());

            Object allCount = json.get("all-count");

            if (allCount != null) {
                Double total = (Double) allCount;
                if (total > 500) {
                    switch (timeEnum) {
                        case DAY:
                            while (startTime.before(endTime)) {
                                Calendar calendar = new GregorianCalendar();
                                calendar.setTime(startTime);
                                calendar.add(Calendar.HOUR_OF_DAY, 1);
                                Date tempTime = calendar.getTime();
                                getSisData(tag, startTime, tempTime.after(endTime) ? endTime : tempTime, TimeEnum.HOUR, allDataList);
                                startTime = tempTime;
                            }
                            break;
                        case HOUR:
                            while (startTime.before(endTime)) {
                                Calendar calendar = new GregorianCalendar();
                                calendar.setTime(startTime);
                                calendar.add(Calendar.MINUTE, 15);
                                Date tempTime = calendar.getTime();
                                getSisData(tag, startTime, tempTime.after(endTime) ? endTime : tempTime, TimeEnum.QUARTER, allDataList);
                                startTime = tempTime;
                            }
                            break;
                        default:
                            while (startTime.before(endTime)) {
                                Calendar calendar = new GregorianCalendar();
                                calendar.setTime(startTime);
                                calendar.add(Calendar.MINUTE, 1);
                                Date tempTime = calendar.getTime();
                                getSisData(tag, startTime, tempTime.after(endTime) ? endTime : tempTime, TimeEnum.SECOND, allDataList);
                                startTime = tempTime;
                            }
                            break;
                    }
                } else {
                    TagResponse tagResponse = gson.fromJson(responseStr, TagResponse.class);
                    List<TagData> dataList = tagResponse.getHistory();
                    if (dataList != null && !dataList.isEmpty()) {
                        allDataList.addAll(dataList);
                    }
                }
            }
        }
    }

    private static String doGetSisInterface(String tag, Date startTime, Date endTime) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");

        String startTimeStr = simpleDateFormat.format(startTime);
        String endTimeStr = simpleDateFormat.format(endTime);
        Map<String, String> param = new HashMap<>();
        param.put("tag", tag);
        param.put("from", startTimeStr);
        param.put("to", endTimeStr);

        String responseStr = HttpClientUtil.doGet(sisUrl, param);

        //-----------测试模拟数据------------
//        Map<String, Object> map = new HashMap<>();
//        SimpleDateFormat zSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
//        List<TagData> dataList = new ArrayList<>();
//        while (startTime.before(endTime)) {
//            TagData data = new TagData();
//            data.setTag("realflex6/NTW/TLC_2_CLSTAT/A/AIRV0LL01");
//            data.setTime(zSdf.format(startTime));
//            data.setValue(BigDecimal.valueOf(111));
//            Calendar calendar = new GregorianCalendar();
//            calendar.setTime(startTime);
//            calendar.add(Calendar.SECOND, 10);
//            startTime = calendar.getTime();
//            dataList.add(data);
//        }
//        map.put("tag", "realflex6/NTW/TLC_2_CLSTAT/A/AIRV0LL01");
//        map.put("history", dataList);
//        map.put("all-count", dataList.size());
//
//        String responseStr = new GsonBuilder()
//                .setLongSerializationPolicy(LongSerializationPolicy.STRING)
//                .setDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX")
//                .create().toJson(map);
//        log.info(tag + "调用sis3接口");


//        String responseStr = "{\"tag\":\"realflex6/NTE1/MUKWU2_RWPS/A/AIRT0LL07\",\"from\":\"2023-08-14T12:00:00-04:00\",\"to\":\"2023-08-14T13:00:00-04:00\",\"history\":[{\"time\":\"2023-08-15 00:01:06+0800\",\"value\":4.88625},{\"time\":\"2023-08-15 00:03:13+0800\",\"value\":4.938125},{\"time\":\"2023-08-15 00:07:39+0800\",\"value\":4.886875},{\"time\":\"2023-08-15 00:07:53+0800\",\"value\":4.9375},{\"time\":\"2023-08-15 00:19:59+0800\",\"value\":4.886875},{\"time\":\"2023-08-15 00:20:59+0800\",\"value\":4.938125},{\"time\":\"2023-08-15 00:22:30+0800\",\"value\":4.885},{\"time\":\"2023-08-15 00:23:09+0800\",\"value\":4.93625},{\"time\":\"2023-08-15 00:24:57+0800\",\"value\":4.88375},{\"time\":\"2023-08-15 00:25:11+0800\",\"value\":4.938125},{\"time\":\"2023-08-15 00:26:25+0800\",\"value\":4.8875},{\"time\":\"2023-08-15 00:27:56+0800\",\"value\":4.94},{\"time\":\"2023-08-15 00:28:14+0800\",\"value\":4.88875},{\"time\":\"2023-08-15 00:30:48+0800\",\"value\":4.939375},{\"time\":\"2023-08-15 00:31:09+0800\",\"value\":4.888125},{\"time\":\"2023-08-15 01:01:06+0800\",\"value\":4.88625},{\"time\":\"2023-08-15 01:03:13+0800\",\"value\":4.938125},{\"time\":\"2023-08-15 01:07:39+0800\",\"value\":4.886875},{\"time\":\"2023-08-15 01:07:53+0800\",\"value\":4.9375},{\"time\":\"2023-08-15 01:19:59+0800\",\"value\":4.886875},{\"time\":\"2023-08-15 01:20:59+0800\",\"value\":4.938125},{\"time\":\"2023-08-15 01:22:30+0800\",\"value\":4.885},{\"time\":\"2023-08-15 01:23:09+0800\",\"value\":4.93625},{\"time\":\"2023-08-15 01:24:57+0800\",\"value\":4.88375},{\"time\":\"2023-08-15 01:25:11+0800\",\"value\":4.938125},{\"time\":\"2023-08-15 01:26:25+0800\",\"value\":4.8875},{\"time\":\"2023-08-15 01:27:56+0800\",\"value\":4.94},{\"time\":\"2023-08-15 01:28:14+0800\",\"value\":4.88875},{\"time\":\"2023-08-15 01:30:48+0800\",\"value\":4.939375},{\"time\":\"2023-08-15 01:31:09+0800\",\"value\":4.888125}],\"all-count\":15,\"unit\":\"M\"}";
//        //-----------测试模拟数据------------
        return responseStr;
    }
}
